﻿
using System ;

using MskEdit.Sdk ;
using MskEdit.Dxf.Representation ;


namespace MskEdit.Dxf.Model
{

    public class DxfBlock : DxfStructBase
    {
        private static DxfSignature         signature_      = new DxfSignature( "0", "BLOCK", "0", "" ) ;
        private static ConstructorHandler   constructor_    = (a, b) => { return new DxfBlock(a, b) ; } ;
        private        Lazy<SdkSubrange>    entitiesSubrange_ ;
        private        Lazy<DxfEntity[]>    entities_ ;
        
        
        private static SdkSubrange getEntitiesSubrange( string[] allLines, SdkSubrange subrange ) {
        
            int lineNo = subrange.Begin + 2 ;
            DxfCodeTagPair codeTagPair = new DxfCodeTagPair( "0", "" ) ;
            int? begin = codeTagPair.TryFindFirst( allLines, ref lineNo, null ) ;
            
            if ( !begin.HasValue )
                return new SdkSubrange() ;
                
            DxfSignature  entitiesSignature = new DxfSignature( "0", "", "0", "ENDBLK" ) ;
            
            SdkSubrange? entitesSubrange = entitiesSignature.TryGetSubrange( allLines, ref lineNo, null ) ;
            
            if ( ! entitesSubrange.HasValue )
                return new SdkSubrange() ;
                
            return entitesSubrange.Value ;
        }


        private DxfBlock( string[] allLines, SdkSubrange subrange ) : base ( allLines, subrange ) {
            entitiesSubrange_ = new Lazy<SdkSubrange>( () => { return getEntitiesSubrange( allLines, subrange ) ; } ) ;
            entities_ = new Lazy<DxfEntity[]>( () => { return DxfEntities.getEntities( allLines, entitiesSubrange_.Value ) ; } ) ;
        }
        
        
        public static DxfBlock TryFrom( string[] allLines, ref int lineNo, DxfBlock fallbackValue ) {
            return (DxfBlock) DxfStructBase.TryConstruct( allLines, ref lineNo, signature_, constructor_, fallbackValue ) ;
        }
        
        
        public string TryGetAttrdefPrompt( string attribTag, string fallbackValue ) {
        
            string prompt = null ;
            
            foreach ( DxfEntity dxfEntity in entities_.Value ) {
                
                DxfAttdefEntity dxfAttrdefEntity = dxfEntity as DxfAttdefEntity ;
                if ( dxfAttrdefEntity == null )
                    continue ;
                    
                if ( dxfAttrdefEntity.Tag != attribTag )
                    continue ;
                    
                prompt = dxfAttrdefEntity.Prompt ;
                break ;
            }
            
            if ( prompt == null )
                return fallbackValue ;
                
            return prompt ;
        }


        public string Name {
            get { return this.TryFindFirstValue( "2", "" ) ; }
        }
        
        
        public DxfEntity[] Entities {
            get { return entities_.Value ; }
        }

    }
}
